var XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

function _DOM_clearChildren(parent) {
   while (parent.childNodes.length>0) {
      parent.removeChild(parent.childNodes.item(0));
   }
}

var Entry = {
   actor: null,
   categories: [],
   categoryList: null,
   tabbox: null,
   linkList: null,
   elements: {},
   editor: {
      doc: null,
      control: null,
      init: function() {
         this.control = document.getElementById('editor');
         this.doc = this.control.contentWindow.document;
         /*
         this.control.setAttribute("src","chrome://atomic/content/blank.html");
         var currentEdit = this;
         setTimeout(function() {
            try {
               currentEdit.control.makeEditable("html",true);
               //currentEdit.doc = currentEdit.control.contentWindow.document;
            } catch (ex) {
               alert(ex);
            }
         },
            500
         );
          */
      },
      bold: function() {
         this.doc.execCommand("bold", false, null);
      },
      italic: function() {
         this.doc.execCommand("italic", false, null);
      },
      link: function() {
      }
   },
   init: function(type,obj) {
      document.title = obj.title;
      this.type = type;
      this.entry = obj.entry;
      this.actor = obj;
      if (this.type=="description") {
         this.editor.init();
         this.initDescriptionEntry();
      } else if (this.type=="section") {
         this.elements['title'] = document.getElementById('title');
         this.editor.init();
         this.initSectionEntry();
      } else {
         this.elements['title'] = document.getElementById('title');
         this.elements['summary'] = document.getElementById('summary');
         this.elements['url'] = document.getElementById('url');
         this.initResourceEntry();
      }
   },
   initDescriptionEntry: function() {
      this.initContent();
   },
   initSectionEntry: function() {
      //alert("Initializing entry");
      var title = this.entry.getTitle();
      this.elements['title'].value = title.xml.textContent;
      this.initContent();
   },
   initResourceEntry: function() {
      //alert("Initializing entry");
      var title = this.entry.getTitle();
      this.elements['title'].value = title.xml.textContent;
      var summary = this.entry.getSummary();
      if (summary) {
         this.elements['summary'].value = summary.xml.textContent;
      }
      var link = this.entry.getAlternateLink();
      if (link) {
         this.elements['url'].value = link.getAttribute("href");
      }
   },
   initContent: function() {
      var content = this.entry.getContent();
      if (content) {
         var div = content.getXHTMLContent();
         var sourceEditor = document.getElementById('entry-xhtml-source');
         var serializer = new XMLSerializer();
         sourceEditor.value = serializer.serializeToString(div);
         var xhtmlDoc = this.editor.doc;
         var editorDiv = xhtmlDoc.getElementById('content');
         if (div) {
            var current = div.firstChild;
            while (current) {
               editorDiv.appendChild(editorDiv.ownerDocument.importNode(current,true));
               current = current.nextSibling;
            }
         }
      }
      this.sourceTab = false;
      this.editor.control.focus();
      this.editor.control.contentWindow.tinyMCE.execCommand("mceAddControl",false,"content");         
   },
   switchToXHTMLTab: function(index) {
      if (index==0) {
         this.switchToXHTMLFormatted();
      } else {
         this.switchToXHTMLSource();
      }
   },
   switchToXHTMLFormatted: function() {
      if (!this.sourceTab) {
         return;
      }
      this.sourceTab = false;
      var result = this.parseXHTMLSource();
      if (result.wellFormed) {
         this.editor.control.contentWindow.tinyMCE.execCommand("mceRemoveControl",false,"content");         
         var xhtmlDoc = this.editor.doc;
         this.editor.control.focus();
         var editorDiv = xhtmlDoc.getElementById('content');
         _DOM_clearChildren(editorDiv);
         var current = result.div.firstChild;
         while (current) {
            editorDiv.appendChild(editorDiv.ownerDocument.importNode(current,true));
            current = current.nextSibling;
         }
         this.editor.control.contentWindow.tinyMCE.execCommand("mceAddControl",false,"content");         
      } else {
         document.getElementById("xhtml-content-tabs").selectedIndex = 1;
      }
   },
   switchToXHTMLSource: function() {
      if (this.sourceTag) {
         return;
      }
      this.sourceTab = true;
      var xhtmlDoc = this.editor.doc;
      var xmlString = this.editor.control.contentWindow.tinyMCE.getContent();
      var sourceEditor = document.getElementById('entry-xhtml-source');
      sourceEditor.value = "<div xmlns='http://www.w3.org/1999/xhtml'>\n"+xmlString+"\n</div>";
   },
   parseXHTMLSource: function() {
      var sourceEditor = document.getElementById('entry-xhtml-source');
      var desc = document.getElementById("xhtml-xml-errors");             
      _DOM_clearChildren(desc);
      var xmlParser = new DOMParser();
      var xmlDocument = xmlParser.parseFromString(sourceEditor.value, 'text/xml');
      var roottag = xmlDocument.documentElement; 
      var ok = true;
      if ((roottag.tagName == "parsererror") &&
          (roottag.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml")) {
         desc.appendChild(desc.ownerDocument.createTextNode(roottag.firstChild.textContent));
         ok = false;
      } else {
         if (roottag.localName!="div" ||
             roottag.namespaceURI!="http://www.w3.org/1999/xhtml") {
            ok = false
            desc.appendChild(desc.ownerDocument.createTextNode("The div wrapper element is missing."));
         }
      }
      return {
         wellFormed: ok,
         div: roottag
      }
   },
   doSave: function() {
      if (this.type=="description") {
         if (this.sourceTab) {
            var result = this.parseXHTMLSource()
            if (!result.wellFormed) {
               alert("Cannot save entry as the XHTML is not well-formed.");
               return;
            }
         }
         // Update entry
         var titleText = this.entry.getTitle();
         titleText.setTextContent("Description");
         titleText.type = "text";
         this.ensureCategory();
         this.updateContent();
      } else if (this.type=="section") {
         if (this.sourceTab) {
            var result = this.parseXHTMLSource()
            if (!result.wellFormed) {
               alert("Cannot save entry as the XHTML is not well-formed.");
               return;
            }
         }
         // Update entry
         var titleText = this.entry.getTitle();
         titleText.setTextContent(document.getElementById('title').value);
         titleText.type = "text";
         this.ensureCategory();
         this.updateContent();
      } else if (this.type=="resource") {
         // Update entry
         var titleText = this.entry.getTitle();
         titleText.setTextContent(document.getElementById('title').value);
         titleText.type = "text";
         var summary = document.getElementById('summary').value;
         var summaryText = this.entry.getSummary();
         if (summary) {
            if (!summaryText) {
               summaryText = this.entry.getSummary(true);
            }
            summaryText.type = "text";
            summaryText.setTextContent(summary);
         } else if (summaryText) {
            this.entry.xml.removeChild(summaryText.xml);
         }
         var link = this.entry.getAlternateLink();
         if (link) {
            link.setAttribute("href",this.elements['url'].value);
         } else {
            this.entry.addLink("alternate",this.elements['url'].value);
         }
         this.ensureCategory();
      }
      this.buttonsDisabled(true);
      this.actor.doSave(this);   
   },
   ensureCategory: function() {
      var categories = this.entry.getCategories();
      var entryType = null;
      for (var i=0; i<categories.length; i++) {
         if (categories[i].scheme=="http://www.atomojo.org/O/type/entry/") {
            if (!entryType) {
               entryType = categories[i];
            } else {
               this.entry.removeCategory(categories[i]);
            }
         }
      }
      if (!entryType) {
         this.entry.addCategory("http://www.atomojo.org/O/type/entry/",this.type);
      } else {
         entryType.term = this.entry.type;
      }
   },
   doCancel: function() {
      this.actor.doCancel();
      window.close();
   },
   updateContent: function() {
      var content = this.entry.getContent(true);
      if (!this.sourceTab) {
         var xmlString = this.editor.control.contentWindow.tinyMCE.getContent();
         var sourceEditor = document.getElementById('entry-xhtml-source');
         sourceEditor.value = "<div xmlns='http://www.w3.org/1999/xhtml'>\n"+xmlString+"\n</div>";
         LOG.debug("From editor:\n"+sourceEditor.value);
      }
      var result = this.parseXHTMLSource();
      if (!result.wellFormed) {
         throw "XHTML source is not well-formed.";
      }
      content.type = "xhtml";
      content.setNodeContent(result.div);
   },
   doDelete: function() {
      if (this.tabbox.selectedIndex==1) {
         this.deleteSelectedCategories();
      }
   },
   onSuccess: function() {
      setTimeout(function() { window.close(); },100);
   },
   onFailure: function(message) {
      var desc = document.getElementById('message');
      if (desc.firstChild) {
         desc.removeChild(desc.firstChild);
      }
      desc.appendChild(document.createTextNode(message));
      this.buttonsDisabled(false);
   },
   buttonsDisabled: function(flag) {
      document.getElementById('save').disabled = flag;
      document.getElementById('cancel').disabled = flag;
      document.getElementById('revert').disabled = flag;
   }
}
